<?php

namespace App\Controller\Admin;

use App\Model\ChatModel;
use App\Repository\ChatRepository;
use App\Repository\ConfigRepository;
use App\Service\MoneyService;
use App\Setting\ChatSetting;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use Symfony\Component\HttpFoundation\Request;
use App\Base\BaseController4Admin;
use App\Entity\Chat as Entity;

/**
 * @route("/admin/")
 */
class ChatController extends BaseController4Admin
{

    /**
     * @route("Chat/add",name="ChatPreAdd")
     */
    public function add()
    {
        $uid = $this->needToBeAdmin();
        //通用代码
        $this->setSetting(new ChatSetting($this->getDoctrine()));
        $entity = "";
        if (!$entity) {$entity = new $this->entitySetting->entityPath();}
        $setting = new ChatSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig(),$this->generateUrl("ChatDoAdd"));
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => true,
        );
        return $this->show("Admin/Chat/edit.php.twig",$data);
    }

    /**
     * @route("Chat/reply",name="ChatPreReply")
     */
    public function ChatPreReply(ChatRepository $chatRepository)
    {
        if(!$id = $this->getParamRequired("id")){die("参数缺失");}
        $lastChat = $chatRepository->find($id);
        $uid = $this->needToBeAdmin();
        //通用代码
        $this->setSetting(new ChatSetting($this->getDoctrine()));
        $entity = "";
        if (!$entity) {$entity = new Entity();}
        $entity->setCreateAt(new \DateTime())
            ->setStatus(1)
            ->setFlag(1)
            ->setFromUser($lastChat->getToUser())
            ->setToUser($lastChat->getFromUser())
            ->setLink($lastChat->getLink())
        ;
        $setting = new ChatSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->viewConfig(),$this->generateUrl("ChatDoAdd"));

        //扣除用户积分
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => true,
        );
        return $this->show("Admin/Chat/edit.php.twig",$data);
    }

    /**
     * @route("Chat/pay",name="ChatPreReplyPay")
     */
    public function ChatPreReplyPay(ChatRepository $chatRepository)
    {
        if(!$id = $this->getParamRequired("id")){die("参数缺失");}
        $lastChat = $chatRepository->find($id);

        $setting = new ChatSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($lastChat,$setting->viewPay(),$this->generateUrl("ChatDoAdd"));

        //扣除用户积分
        $data = array(
            "title" => "咨询扣费",
            "show"   => $from->createView(),
            "isAdd"   => true,
        );
        return $this->show("Admin/Chat/pay.php.twig",$data);
    }

    /**
     * @route("Chat/pay/do",name="ChatPreReplyPayDo")
     */
    public function ChatPreReplyPayDo(ChatRepository $chatRepository,ConfigRepository $configRepository ,MoneyService $moneyService)
    {
        if(!$id = $this->getParamRequired("id")){die("参数缺失");}
        if(!$price = $this->getParamRequired("price")){$price = 0;}



        $Chat = $chatRepository->find($id);
        $conf = $configRepository->findAll();
        $config = [];
        foreach ($conf as $row) {
            $config[$row->getK()] = $row->getV();
        }
        //保证金支付金额设置
        $fee = $configRepository->getByK("FEE_CHAT_MASTER");


        if ($price) {
            $fee = $price;
        }
        $userMoney = $moneyService->getUserMoney($Chat->getFromUser());
        if ($userMoney["jifen"] < $fee) {
            return $this->json_out(400,"积分不足", $Chat);
        }
        $moneyService->mod($Chat->getFromUser(),$fee * -1,MoneyService::__MONEY_JI_FEN__,202,"人工解答");

        $histories = $chatRepository->findBy(array("link"=>$Chat->getLink(),"status"=>1));
//        dd($histories);
        if ($histories) {
            //更新所有的已回复数据为已扣费
            foreach ($histories as $log) {
                $log->setStatus(2);
                $this->myEm()->persist($log);
            }
            $this->myEm()->flush();
        }

        return $this->json_out(200,"扣费成功");
    }

    /**
     * @route("Chat/add/do",name="ChatDoAdd")
     *
     *
     */
    public function doAdd(Request $request)
    {
        $uid = $this->needToBeAdmin();
        $entity = new Entity();
        if (!$entity) {
            $entity = new $this->entitySetting->entityPath();
        }
        $setting = new ChatSetting($this->getDoctrine());
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            /**@var $entity Entity*/
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $urlData = [];//传参
            return $this->js_out("保存成功",$this->generateUrl("ChatLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("ChatPreAdd"));
        }
    }

    /**
     * @route("Chat/edit/{id}",name="ChatPreEdit")
     */
    public function edit(Entity $entity)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new ChatSetting($this->getDoctrine()));
        $setting = new ChatSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig(),$this->generateUrl("ChatDoEdit",["id"=>$entity->getId()]));
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => false,
        );
        return $this->show("Admin/Chat/edit.php.twig",$data);
    }

    /**
     * @route("Chat/edit/{id}/do",name="ChatDoEdit")
     *
     *
     */
    public function doEdit(Request $request,Entity $entity)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new ChatSetting($this->getDoctrine()));
        $setting = new ChatSetting($this->getDoctrine());
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            /**@var $entity Entity*/
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $urlData = [];
            return $this->js_out("保存成功",$this->generateUrl("ChatLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("ChatPreEdit",array("id"=>$entity->getId())));
        }
    }

    /**
     * @route("Chat",name="ChatLists")
     */
    public function lists()
    {
        $uid = $this->needToBeAdmin();
        //私有部分
        $tools = array();
//        $tools["flag"] = array(
//            ["id"=>1,"name" => "问军师"],
//            ["id"=>2,"name" => "问AI"]
//        );
        $tools["status"] = array(
            ["id"=>0,"name" => "未回复"],
            ["id"=>1,"name" => "已处理"]
        );
        $tools["toUser"] = array(
            ["id"=>1,"name" => "不看我的回复"]
        );

        //通用部分
        $this->setSetting(new ChatSetting($this->getDoctrine()));
        /*分页配置*/
        if (!$page   = $this->getParamRequired("page")) { $page = 1;}
        $per_page   = $this->entitySetting->perPage;
        $model = new ChatModel($this->getDoctrine());
        $params = array();
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ($key == "toUser" && $val == 1) {
                    $params["conditions"][$this->entitySetting->table][$key]["isNull"]=true;
                    continue;
                }
                if ($val === "") {
                    continue;
                }
                $params["conditions"][$this->entitySetting->table][$key]["eq"]=$val;
            }
        }
        $params["conditions"][$this->entitySetting->table]["flag"]["eq"]=1;
        if ($txtKeywords) {
            $params["textKey"] = "%$txtKeywords%";
        }
        $table = str_replace("_","",$this->entitySetting->table);
        $params["groupBy"][$table]=array("id");
        $lists = $model->getAdminLists($params,$page * $per_page - $per_page,$per_page);

        //$lists = $this->getLists($page,$per_page);
        $total = $lists["total"];
        $this->smartFormat($lists["data"]);

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl("ChatTools"),
            "addUrl"=>$this->generateUrl("ChatPreAdd"),
        );
        $entityCnName = $this->entitySetting->entityCnName;
        $config = $this->entitySetting->formConfig();
        $data = array(
            'title'     => "$entityCnName 列表",
            "tools"     => $tools,
            'urls'      => $urls,
            "config"    => $config,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl("ChatLists"),$total,$per_page),
        );
        return $this->show("Admin/Chat/list.php.twig",$data);
    }

    /**
     * @route("Chat/tools",name="ChatTools")
     */
    public function tools(Request $request)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new ChatSetting($this->getDoctrine()));
        return $this->comTools($request);
    }

    /**
     * @route("Chat/copy/{id}",name="ChatDoCopy")
     *
     * @Method({"GET", "POST"})
     */
    public function doCopy(Request $request,Entity $entity)
    {
        $tmp = $entity;
        $tmp = $this->toArray($tmp);
        $en = new Entity();
        foreach ($tmp as $key => $value) {
            if ($key == "id") {continue;}
            $funcGet = "get".ucfirst($key);
            $funcSet = "set".ucfirst($key);
            $en->$funcSet($entity->$funcGet());
        }
        $this->myEm()->persist($en);$this->myEm()->flush();
        return $this->redirectToRoute("ChatLists");
    }

}
